//
//  realNameVC.m
//  jiaKaoZhuShou
//
//  Created by 金艺社 on 2018/6/14.
//  Copyright © 2018年 金艺社. All rights reserved.
//

#import "realNameVC.h"
#import "leftTitleRightContentView.h"
#import "certificationCompleteVC.h"
@interface realNameVC () {
    int btnBackColor;
    leftTitleRightContentView *V1;
    leftTitleRightContentView *V2;
    leftTitleRightContentView *V3;
    int times;
}

@end

@implementation realNameVC
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"实名认证";
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    
    UILabel *redLab = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 25)];
    redLab.backgroundColor = [UIColor custom_color:@"#F1D6D6"];
    redLab.textColor = [UIColor custom_color:@"#A91E23"];
    redLab.font = [UIFont systemFontOfSize:10];
    redLab.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:redLab];
    //创建富文本
    NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:@"   请确保以下信息真实有效"];
    //lab上添加图片
    NSTextAttachment *textAttach = [[NSTextAttachment alloc]init];
    textAttach.image = [UIImage imageNamed:@"light"];
    textAttach.bounds = CGRectMake(0, 0, 10, 10);
    //创建带有图片的富文本
    NSAttributedString *imgString = [NSAttributedString attributedStringWithAttachment:textAttach];
    //将图片放在最后一位
    //[attri appendAttributedString:string];
    //将图片放在第一位
    [attri insertAttributedString:imgString atIndex:0];
    redLab.attributedText = attri;
    
    __weak typeof(self)weakSelf = self;
    V1 = [leftTitleRightContentView new];
    V1.textChangeBlock = ^(BOOL isCertification) {
        if (isCertification) {
            [weakSelf changeColor:1];
        }else {
            [weakSelf changeColor:-1];
        }
    };
    [V1 setTitle:@"姓       名：" font:14 titleColor:@"#333333" layout:@[@21, @18]];
    [V1 setPlaceholder:@"请输入您的真实姓名" font:14 layout:@[@108, @18]];
    [self.view addSubview:V1];
    [V1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(@0);
        make.top.equalTo(redLab.mas_bottom).offset(10);
        make.height.equalTo(@50);
    }];
    
    V2 = [leftTitleRightContentView new];
    V2.textChangeBlock = ^(BOOL isCertification) {
        if (isCertification) {
            [weakSelf changeColor:1];
        }else {
            [weakSelf changeColor:-1];
        }
    };
    [V2 setTitle:@"身份证号：" font:14 titleColor:@"#333333" layout:@[@21, @18]];
    [V2 setPlaceholder:@"请输入您的身份证号" font:14 layout:@[@108, @18]];
    V2.content_tf.keyboardType = UIKeyboardTypeNumberPad;
    [self.view addSubview:V2];
    [V2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(@0);
        make.top.equalTo(V1.mas_bottom).offset(1);
        make.height.equalTo(@50);
    }];
    
    V3 = [leftTitleRightContentView new];
    V3.textChangeBlock = ^(BOOL isCertification) {
        if (isCertification) {
            [weakSelf changeColor:1];
        }else {
            [weakSelf changeColor:-1];
        }
    };
    [V3 setTitle:@"支付宝账号：" font:14 titleColor:@"#333333" layout:@[@21, @18]];
    [V3 setPlaceholder:@"请输入您的支付宝帐号" font:14 layout:@[@108, @18]];
    V3.content_tf.keyboardType = UIKeyboardTypeNumberPad;
    [self.view addSubview:V3];
    [V3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(@0);
        make.top.equalTo(V2.mas_bottom).offset(1);
        make.height.equalTo(@50);
    }];
    
    UIButton *certification = [UIButton new];
    certification.enabled = NO;
    certification.backgroundColor = [UIColor custom_color:@"#999999"];
    [certification setTitle:@"前往认证" forState:0];
    [certification setTitleColor:[UIColor custom_color:@"#FFFFFF"] forState:0];
    certification.titleLabel.font = [UIFont systemFontOfSize:15];
    certification.layer.masksToBounds = YES;
    certification.layer.cornerRadius = 22;
    [certification addTarget:self action:@selector(certificationClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:certification];
    [certification mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(V3.mas_bottom).offset(20);
        make.left.equalTo(@20);
        make.right.mas_equalTo(-20);
        make.height.equalTo(@44);
    }];
}
- (void)changeColor:(int)change {
    UIButton *btn = (UIButton *)self.view.subviews.lastObject;
    btnBackColor = btnBackColor + change;
    if (btnBackColor == 3) {
        btn.backgroundColor = [UIColor custom_color:@"#A91E23"];
        btn.enabled = YES;
    }else {
        btn.backgroundColor = [UIColor custom_color:@"#999999"];
        btn.enabled = NO;
    }
}

- (void)certificationClick {
    //芝麻认证 url 后台获取
    [self InitializeRequest];
}
#pragma mark --- 芝麻认证 
- (void)InitializeRequest {
    NSDictionary *dic = @{
                          @"token":USERTOKEN,
                          @"realName":V1.content_tf.text,
                          @"idCard":V2.content_tf.text,
                          @"aliPayAccount":V3.content_tf.text
                          };
    __weak typeof(self) weakSelf = self;
    NSString *url = [NSString stringWithFormat:@"%@", [[apiManger shareApiManger] InitializeCertification]];
    [networkManger PostHttpDataWithUrlStr:url Dic:dic SuccessBlock:^(id responseObject) {
        if ([responseObject[@"rcd"] isEqualToString:R0001]) {
            [weakSelf getCertificationUrlWithNo:responseObject[@"biz_no"] andName:responseObject[@"realName"] andIdCard:responseObject[@"idCard"]];
        }else if ([responseObject[@"rmg"] isEqualToString:@"用户不存在"]) {
            [MBProgressHUD gk_toastShowMessage:@"请先登录"];
        }else{
            [MBProgressHUD gk_toastShowMessage:responseObject[@"rmg"]];
        }
    } FailureBlock:^(id error) {
        [MBProgressHUD gk_toastShowMessage:@"请求失败"];
    }];
}
- (void)getCertificationUrlWithNo:(NSString *)bizNo andName:(NSString *)name andIdCard:(NSString *)card{
        NSDictionary *dic = @{
                              @"token":USERTOKEN,
                              @"realName":name,
                              @"idCard":card,
                              @"biz_no":bizNo
                              };
    __weak typeof(self) weakSelf = self;
    NSString *url = [NSString stringWithFormat:@"%@", [[apiManger shareApiManger] GetVerificatioUrl]];
    [networkManger PostHttpDataWithUrlStr:url Dic:dic SuccessBlock:^(id responseObject) {
        if ([responseObject[@"rcd"] isEqualToString:R0001]) {
            [weakSelf doVerify:responseObject[@"url"]];
        }else if ([responseObject[@"rmg"] isEqualToString:@"用户不存在"]) {
            [MBProgressHUD gk_toastShowMessage:@"请先登录"];
        }else{
            [MBProgressHUD gk_toastShowMessage:responseObject[@"rmg"]];
        }
    } FailureBlock:^(id error) {
        [MBProgressHUD gk_toastShowMessage:@"请求失败"];
    }];
}
//调用支付宝认证
- (void)doVerify:(NSString *)url {
    // 这里使用固定appid 20000067
    NSString *alipayUrl = [NSString stringWithFormat:@"alipays://platformapi/startapp?appId=20000067&url=%@",
                           [self URLEncodedStringWithUrl:url]];
    if ([self canOpenAlipay]) {
        if (@available(iOS 10.0, *)) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:alipayUrl] options:@{} completionHandler:^(BOOL success) {//跳转到支付宝芝麻认证
                if (success) {
                    NSLog(@"认证成功");
//                    certificationCompleteVC *VC = [certificationCompleteVC new];
//                    [self.navigationController pushViewController:VC animated:YES];
                }
            }];
        }
    } else {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:@"是否下载并安装支付宝完成认证?"
                                                          delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"好的", nil];
        [alertView show];
    }
}

//字符串encode
- (NSString *)URLEncodedStringWithUrl:(NSString *)url {
    NSString *encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL,(CFStringRef)url,NULL,(CFStringRef) @"!'();:@&=+$,%#[]|",kCFStringEncodingUTF8));
    return encodedString;
}
//是否安装支付宝
- (BOOL)canOpenAlipay {//
    return [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"alipay:"]];
}
//如果没有安装支付宝 就跳转至App Store下载支付宝
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        NSString *appstoreUrl = @"itms-apps://itunes.apple.com/app/id333206289";
        if (@available(iOS 10.0, *)) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:appstoreUrl] options:@{} completionHandler:nil];
        } else {
            // Fallback on earlier versions
        }
    }else {
        
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
